package top.kaoshanji.ch02;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.ch02.randomAccess.DataIO;
import top.kaoshanji.ch02.randomAccess.Employee;

import java.io.*;
import java.time.LocalDate;

/**
 * 代码清单 ch02-02：RandomAccessFile类示例(2.2.2节)
 * author kaoshanji
 * ^_^
 * create time 2024/12/6 14:59
 */
public class RandomAccessTest {

    private static final Logger logger = LogManager.getLogger(RandomAccessTest.class);

    static final String EMPLOYEE_FILE_NAME = "ch02-02-employee.dat";

    public static void main(String[] args) throws IOException {
        logger.info("...代码清单 ch02-02：RandomAccessFile类示例(2.2.2节)...");

        var staff = new Employee[3];

        staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
        staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
        staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

        try (var out = new DataOutputStream(new FileOutputStream(EMPLOYEE_FILE_NAME))) {
            // 写入数据
            for (Employee e: staff) {
                writeDate(out, e);
            }
        }

        try (var in = new RandomAccessFile(EMPLOYEE_FILE_NAME, "r")) {

            int n = (int)(in.length() / Employee.RECORD_SIZE);
            var newStaff = new Employee[n];

            // 读取数据...i--....
            for (int i = n - 1; i >= 0; i--) {
                newStaff[i] = new Employee();
                in.seek(i * Employee.RECORD_SIZE);
                newStaff[i] = readData(in);
            }

            // 打印内容
            for (Employee e: newStaff) {
                System.out.println(e);
            }
        }

    }


    public static void writeDate(DataOutput out, Employee e) throws IOException {

        DataIO.writeFixedString(e.getName(), Employee.NAME_SIZE, out);
        out.writeDouble(e.getSalary());

        LocalDate hireDay = e.getHireDay();
        out.writeInt(hireDay.getYear());
        out.writeInt(hireDay.getMonthValue());
        out.writeInt(hireDay.getDayOfMonth());

    }

    public static Employee readData(DataInput in) throws IOException {

        String name = DataIO.readFixedString(Employee.NAME_SIZE, in);
        double salary = in.readDouble();
        int y = in.readInt();
        int m = in.readInt();
        int d = in.readInt();
        return new Employee(name, salary, y, m - 1, d);
    }



}
